package com.xiaomi.service.impl;


import com.xiaomi.dao.OrderDao;
import com.xiaomi.dao.impl.OrderDaoImpl;
import com.xiaomi.entity.Cart;
import com.xiaomi.entity.Item;
import com.xiaomi.entity.Orders;
import com.xiaomi.service.CartService;
import com.xiaomi.service.ItemService;
import com.xiaomi.service.OrderService;
import com.xiaomi.utils.RandomUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * TODO
 *
 * @author jy
 * @date 2021/5/26
 */
public class OrderServiceImpl implements OrderService {

    private final OrderDao orderDao = new OrderDaoImpl();
    private final CartService cartService = new CartServiceImpl();
    private final ItemService itemService = new ItemServiceImpl();

    @Override
    public int addOrderAndItemList(String uid, String aid, String num) {
        Orders orders = new Orders();
        orders.setUid(Integer.parseInt(uid));
        orders.setAid(Integer.parseInt(aid));
        orders.setMoney(new BigDecimal(num));
        //随机生成订单号
        String oid = RandomUtils.createOrderId();
        orders.setOid(oid);
        //订单时间
        orders.setTime(new Date());
        //订单状态
        orders.setState(1);
        List<Item> list = new ArrayList<>();
        List<Cart> carts = cartService.showCartsByUid(Integer.parseInt(uid));
        int count = 0;
        try {
            count = orderDao.insertOrder(orders);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for (Cart cart : carts) {
            Item item = new Item();
            item.setPid(cart.getPid());
            item.setNum(cart.getNum());
            item.setMoney(cart.getMoney());
            item.setOid(oid);
            list.add(item);
        }
        for (Item item : list) {
            count = itemService.insertItem(item);
        }
        return count;
    }

    @Override
    public List<Orders> getOrderSetAddress(String uid) {
        try {
            if (uid != null && !"".equals(uid)) {
                return orderDao.getOrderSetAddress(Integer.parseInt(uid));
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Orders getOrder(String oid) {
        if (oid != null && !"".equals(oid)) {
            try {
                return orderDao.getOrder(oid);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
}
